package com.qf.iot.utils;

import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.qf.iot.entity.QfTenant;


import java.util.Calendar;
import java.util.Date;

public class JwtUtils {

    public static String genTokenExpireByHour(Object payload,int hour){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR,hour);
        Date expire = instance.getTime();
        //颁发jwt令牌
        String jwtToken = JWT.create()
                //.withHeader()
                .withClaim("userInfo", JSONUtil.toJsonStr(payload))
                //设置过期时间
                .withExpiresAt(expire)
                .sign(Algorithm.HMAC256("qf"));

        return jwtToken;
    }


    public static String genTokenExpireByMinute(Object payload,int minute){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE,minute);
        Date expire = instance.getTime();
        //颁发jwt令牌
        String jwtToken = JWT.create()
                //.withHeader()
                .withClaim("userInfo", JSONUtil.toJsonStr(payload))
                //设置过期时间
                .withExpiresAt(expire)
                .sign(Algorithm.HMAC256("qf"));

        return jwtToken;
    }
    public static QfTenant  paseToken(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("qf")).build();

        DecodedJWT verify =
                jwtVerifier.verify(token);


        return  JSONUtil.toBean(verify.getClaim("userInfo").asString(),QfTenant.class);

    }




}
